﻿using System;
using System.Collections.Generic;
using System.Text;

namespace XLModbus.Tools
{
    public static class ValueHelper
    {
        private static byte[] ASCIIToBytes(this string str)
        {
            List<byte> bytes = new List<byte>();
            for (int i = 0; i < str.Length; i = i + 2)
            {
                bytes.Add(Convert.ToByte(str.Substring(i, 2), 16));
            }
            return bytes.ToArray();
        }

        public static ushort OperationValue(this ushort value, ushort location)
        {
            ushort count = (ushort)(1 << location);
            value |= count;
            return value;
        }
        public static ushort BoolsToUShort(this List<bool> bools, bool isReverse = false)
        {
            ushort value = 0;
            if (bools.Count < 16)
            {
                bools.AddRange(new bool[16 - bools.Count]);
            }
            if (isReverse) { bools.Reverse(); }
            for (int i = 0; i < bools.Count; i++)
            {
                if (bools[i])
                {
                    value |= (ushort)(1 << i);
                }
            }
            return value;
        }

        public static byte[] BoolsToByte(this List<bool> bools, bool isReverse = false)
        {
            List<byte> bytes = new List<byte>();
            byte value = 0;
            int count = bools.Count % 8;
            if (bools.Count < 8)
            {
                bools.AddRange(new bool[8 - bools.Count]);
            }
            if (count > 0)
            {
                bools.AddRange(new bool[8 - count]);
            }
            if (isReverse) { bools.Reverse(); }
            for (int i = 0; i < bools.Count; i++)
            {
                if (bools[i])
                {
                    value |= (byte)(1 << (i % 8));
                }
                if ((i + 1) % 8 == 0)
                {
                    bytes.Add(value);
                    value = 0;
                }
            }
            return bytes.ToArray();
        }
    }
}
